package adb;

import static adb.ADBView.jTextAreaStatus;
import static adb.ADBView.output;
import static adb.ADBView.removeFileinPath;
import static adb.ADBView.separator;
import static adb.LoadingWindows.getJarpath;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.SwingWorker;

public class extractADB extends SwingWorker<Void, String> {

    boolean result = false;
    @Override
    protected Void doInBackground() throws IOException{
        
        String resource = "/adb/resources/";
        String aapt = "aapt";
        String aaptexe = "aapt.exe";
        String adb = "adb";
        String adbexe = "adb.exe";
        String AdbWinApidll = "AdbWinApi.dll";
        String AdbWinUsbApidll = "AdbWinUsbApi.dll";
        String ADBJarPath = getJarpath();
        if (ADBJarPath.contains(".jar")) {
            ADBJarPath = removeFileinPath(ADBJarPath);
        }
        new File(ADBJarPath+separator+"adb").mkdirs();
        saveInputStreamAsFile(getResourceAsStream(resource+aapt),ADBJarPath+separator+"adb"+separator+aapt);
        saveInputStreamAsFile(getResourceAsStream(resource+aaptexe),ADBJarPath+separator+"adb"+separator+aaptexe);
        saveInputStreamAsFile(getResourceAsStream(resource+adb),ADBJarPath+separator+"adb"+separator+adb);
        saveInputStreamAsFile(getResourceAsStream(resource+adbexe),ADBJarPath+separator+"adb"+separator+adbexe);
        saveInputStreamAsFile(getResourceAsStream(resource+AdbWinApidll),ADBJarPath+separator+"adb"+separator+AdbWinApidll);
        saveInputStreamAsFile(getResourceAsStream(resource+AdbWinUsbApidll),ADBJarPath+separator+"adb"+separator+AdbWinUsbApidll);
        return null;
    }   
    public InputStream getResourceAsStream(String resourceName) {
        InputStream is = this.getClass().getResourceAsStream(resourceName);
        return is;
    }
    public void saveInputStreamAsFile(InputStream in,String outPutFile) throws IOException{
        OutputStream out = null;
        try {
            out = new FileOutputStream(outPutFile);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.close();
            in.close();
        } catch (FileNotFoundException ex) {
            output = output + ex + "\n";
            jTextAreaStatus.setText(output);
        } finally {
            try {
                out.close();
            } catch (IOException ex) {
                output = output + ex + "\n";
                jTextAreaStatus.setText(output);
            }
        }
    }

    
}
